package com.lin.zoo.view;

import com.lin.zoo.dao.UserDao;
import com.lin.zoo.util.DataBase;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

public class CommentPage {
    private JFrame frame =new JFrame("评论系统");
    private JButton replyButton,writeButton,delButton,reButton;
    private JTable jTable;
    private DefaultTableModel mol;
    private JScrollPane scrollPane;
    private JPanel panel;
    private JTextField jText,content;
    private Vector<String> rowVector;
    private Vector<Vector<String>> dataVector;
    private Connection con;
    private PreparedStatement state;
    private ResultSet rs;

    public JTextField getContent() {
        return content;
    }

    public void setContent(JTextField content) {
        this.content = content;
    }

    public JButton getReplyButton() {
        return replyButton;
    }

    public void setReplyButton(JButton replyButton) {
        this.replyButton = replyButton;
    }

    public JButton getWriteButton() {
        return writeButton;
    }

    public void setWriteButton(JButton writeButton) {
        this.writeButton = writeButton;
    }

    public JTextField getjText() {
        return jText;
    }

    public void setjText(JTextField jText) {
        this.jText = jText;
    }

    public JButton getDelButton() {
        return delButton;
    }

    public void setDelButton(JButton delButton) {
        this.delButton = delButton;
    }

    public JButton getReButton() {
        return reButton;
    }

    public void setReButton(JButton reButton) {
        this.reButton = reButton;
    }

    public void createAndShowGUI(Object parkId)throws SQLException {
        frame.setVisible(true);
        frame.setSize(1000,400);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        // 显示窗口
        frame.setResizable(false);
        //固定窗口大小不被修改
        frame.setLocationRelativeTo(null);
        //窗口处于中央
        rowVector= new Vector<>();
        rowVector.add("id");
        rowVector.add("评论内容");
        rowVector.add("用户名称");
        rowVector.add("评论时间");
        rowVector.add("评分");//设置列名称文本
        mol = new DefaultTableModel();
        //读取主评论，需要园区id，主评论没有上级的地replyId为0
        try{
            con = DataBase.getCon();
            state = con.prepareStatement("select * from comment where parkid=? and replyid=?");
            state.setObject(1,parkId);
            state.setObject(2,0);
            rs=state.executeQuery();
        }catch (ClassNotFoundException e) {
            System.out.println("数据读取错误"+this.getClass().getName());
        }
        setData(rs);
        DataBase.close(state, con);
        jTable=new JTable(mol);
        jTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        scrollPane=new JScrollPane(jTable);

        TableColumn introductionColumn = jTable.getColumnModel().getColumn(1);
        introductionColumn.setPreferredWidth(800);//修改内容一列的行距

        TableColumn idColumn = jTable.getColumnModel().getColumn(0);
        idColumn.setPreferredWidth(20);//修改id一行的行距

        jTable.setRowHeight(50);
        frame.add(scrollPane,BorderLayout.CENTER);//添加滚轮
        init();
        jText=new JTextField("请在此输入园区评分，此园区平均评分："+ getMark(parkId));//在这个文本栏放置用户输入的评分，同时再此处展示平均评分
        panel.add(jText);
        frame.add(panel,BorderLayout.SOUTH);//放置按钮的panel到页面中
        //写评论
        getWriteButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Vector<String> row= new Vector<>();
                String text=jText.getText();
                String context=content.getText();
                try{
                    con=DataBase.getCon();
                    state=con.prepareStatement("INSERT INTO comment (content,visitorid,date,mark,parkid,replyid) VALUES (?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS);
                    state.setObject(1,context);
                    state.setObject(2, UserDao.getLoginId());
                    state.setObject(3,getdate());
                    state.setObject(4,text);
                    state.setObject(5,parkId);
                    state.setObject(6,0);
                    state.executeUpdate();
                    try (ResultSet rs = state.getGeneratedKeys()) {
                        if (rs.next()) {
                            String id = rs.getString(1);
                            row.add(id);
                            row.add(context);
                            row.add(getName(UserDao.getLoginId()));
                            row.add(getdate());
                            row.add(text);
                            mol.addRow(row);
                        }
                    }

                }//捕捉异常
                catch(ClassNotFoundException | SQLException ex){
                    System.out.println("数据修改错误"+this.getClass().getName());
                }finally{
                    try{
                        DataBase.close(state, con);
                    } catch(SQLException ex){
                        ex.printStackTrace();
                    }
                }
                JOptionPane.showMessageDialog(null, "添加评论成功", null, JOptionPane.PLAIN_MESSAGE);
            }
        });
        //删除评论
        getDelButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int seletedRow=jTable.getSelectedRow();
                seletedRow=jTable.convertRowIndexToModel(seletedRow);
                Object id=jTable.getValueAt(seletedRow+0,0);
                Object visitorName=jTable.getValueAt(seletedRow+0,2);
                if(seletedRow !=-1&&visitorName.equals(getName(UserDao.getLoginId()))) {
                    mol.removeRow(seletedRow);
                    try {
                        con = DataBase.getCon();
                        state = con.prepareStatement("DELETE FROM comment WHERE id=?");
                        state.setObject(1, id);
                        state.executeUpdate();
                        DataBase.close(state, con);
                    } catch (SQLException | ClassNotFoundException ex) {
                        System.out.println("数据删除错误"+this.getClass().getName());
                    }
                    JOptionPane.showMessageDialog(null, "评论删除成功", null, JOptionPane.PLAIN_MESSAGE);
                }
                else
                    JOptionPane.showMessageDialog(null,"并非您的评论", "评论页面", JOptionPane.PLAIN_MESSAGE);
            }
        });
        //修改评论
        getReButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int seletedRow=jTable.getSelectedRow();
                seletedRow=jTable.convertRowIndexToModel(seletedRow);//记录选中行
                Object visitorName=jTable.getValueAt(seletedRow+0,2);
                Object id=jTable.getValueAt(seletedRow+0,0);
                String text=jText.getText();
                String context=content.getText();
                jTable.setValueAt(text,seletedRow,4);
                jTable.setValueAt(context,seletedRow,1);//反馈到界面
                jTable.repaint();
                if(visitorName.equals(getName(UserDao.getLoginId()))) {
                    try {
                        System.out.println(id);
                        con = DataBase.getCon();
                        state = con.prepareStatement("update comment set content=?,mark=? WHERE id=?");//将修改的数据返回数据库
                        state.setObject(1, context);
                        state.setObject(2, text);
                        state.setObject(3, id);
                        state.executeUpdate();
                        DataBase.close(state, con);

                    } catch (SQLException | ClassNotFoundException ex) {
                        System.out.println("数据修改错误" + this.getClass().getName());
                    }
                    JOptionPane.showMessageDialog(null, "评论修改成功", null, JOptionPane.PLAIN_MESSAGE);
                    content.setText("请在此输入需要的内容");
                    jText.setText("请在此输入园区评分，此园区平均评分：" + getMark(parkId));//修改后回到默认的文本提醒
                }
                else
                JOptionPane.showMessageDialog(null, "不是你的评论", null, JOptionPane.PLAIN_MESSAGE);
            }
        });
        //查看回复
        getReplyButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int seletedRow=jTable.getSelectedRow();
                seletedRow=jTable.convertRowIndexToModel(seletedRow);//记录选中行
                Object id=jTable.getValueAt(seletedRow+0,0);
                ReplyPage replyPage=new ReplyPage();
                try {
                    replyPage.createAndShowGUI(parkId,id);
                } catch (SQLException ex) {
                    System.out.println("数据读取错误"+this.getClass().getName());
                }
            }
        });

    }
    //获取当时的时间，返回固定格式的时间字符串
    private String getdate(){
        String time;
        Date now= new Date();//获取新的时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
        time= format.format(now);//以固定格式输出
        return time;
    }
    //获取发表评论的用户的名字
    public String getName(Object id){
        try{String name = null;
            con = DataBase.getCon();
            //获取连接，通过DateBase处理好的通道，连接至mysql数据。
            String sql = "select name FROM user WHERE id=?";//通过id读取user的账户名
            //设定mysql语句
            state = con.prepareStatement(sql);
            //执行sql语句
            state.setObject(1, id);
            ResultSet rx=state.executeQuery();
            while(rx.next()){
                name=rx.getString("name");//从ResultSet中读取名字并放置到name
            }
            return name;
        }//捕捉异常
        catch(ClassNotFoundException | SQLException e){
            System.out.println("名字提取错误"+this.getClass().getName());
        }finally{
            try{
                DataBase.close(state, con);
            } catch(SQLException e){
                System.out.println("名字提取错误"+this.getClass().getName());
            }
        }
        return null;
    }

    public void init(){
        panel=new JPanel();
        content=new JTextField("请在此输入内容");
        replyButton=new JButton("查看回复");
        writeButton=new JButton("写评论");
        delButton=new JButton("删除评论");
        reButton=new JButton("修改评论");//设置按钮的文本

        panel.setLayout(new GridLayout(2,1));

        panel.add(replyButton);
        panel.add(writeButton);
        panel.add(delButton);
        panel.add(reButton);
        panel.add(content);//将按钮和文本添加到承载的panel中
    }
   //获得选中园区的平均评分
    private String getMark(Object parkId){
        float sum=0;//存放所有评分的总和
        int n=0;//存放评分的个数
        float ave;//存放平均分
        try{
            con = DataBase.getCon();
            //获取连接，通过DateBase处理好的通道，连接至mysql数据。
            String sql = "select mark FROM comment WHERE parkid=?";
            //设定mysql语句
            state = con.prepareStatement(sql);
            //执行sql语句
            state.setObject(1, parkId);
            ResultSet rx=state.executeQuery();
            while(rx.next()){
                sum+=rx.getFloat("mark");
                n++;//计算总和，并添加数据的个数
            }
            ave=sum/n;//平均分为总和除以个数
            DecimalFormat decimalFormat=new DecimalFormat("0.0");
            String result=decimalFormat.format(ave);//设置结果的格式为一位小数
            DataBase.close(state, con);//关闭连接
            return result;
        }
        catch (ClassNotFoundException | SQLException e) {
            System.out.println("平均分计算错误"+this.getClass().getName());
        }
        return null;
    }
    //数据读取
    private void setData(ResultSet rs) throws SQLException {
        dataVector = new Vector<>();
        while(rs.next()) {
            Vector<String> vector = new Vector<>();
            for (int i = 1; i <= 5; i++) {//5代表列数
                if (i == 3) {
                    vector.add(getName(rs.getObject(i)));
                }
                else vector.add(rs.getString(i));
            }//添加数据库数据到vector
            dataVector.add(vector);//添加vector数据到dataVector
        }
        mol.setDataVector(dataVector,rowVector);//最后将数据输入至mol
    }

}
